/*
 * @(#)PasswordSecurity.java		       Project:csdn
 * Date:2012-6-1
 *
 * Copyright (c) 2011 CFuture09, Institute of Software, 
 * Guangdong Ocean University, Zhanjiang, GuangDong, China.
 * All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.sinaapp.msdxblog.netsecurity.csdn.util;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.apache.commons.io.FileUtils;

/**
 * @author Geek_Soledad (66704238@51uc.com)
 */
public class PasswordSecurity {

	public static void main(String[] args) {
		passwordToMD5();
	}

	public static void passwordToMD5() {
		try {
			List<String> datas = FileUtils.readLines(new File(
					"C:/Users/msdx/Desktop/丁又专/163账号.txt"));
			String[] splits;
			Collection<String> results = new ArrayList<String>();
			for (String string : datas) {
				splits = string.split(" # ");
				System.out.println(splits[0] + " # " + MD5(splits[1]));
				results.add(splits[0] + " # " + MD5(splits[1]));
			}
			System.out.println("正在写入文件："+"C:/Users/msdx/Desktop/丁又专/163账号密码.txt");
			FileUtils.writeLines(new File("C:/Users/msdx/Desktop/丁又专/163账号加密密码.txt"), results);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * MD5加密。并以16进制形式显示。
	 * 
	 * @param message
	 * @return
	 */
	public static String MD5(String message) {
		try {
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(message.getBytes());
			// 获得密文
			byte[] result = mdInst.digest();
			return toHexString(result);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 字符串转换为16进制。
	 * 
	 * @param b
	 *            byte[]
	 * @return String
	 */
	public static String toHexString(byte[] b) {
		String ret = "";
		for (int i = 0; i < b.length; i++) {
			String hex = Integer.toHexString(b[i] & 0xFF);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			ret += hex.toUpperCase();
		}
		return ret;
	}
}
